<template>
  <div class="chat-page">
    <van-nav-bar
      title="联系客服"
      left-text="返回"
      left-arrow
      @click-left="goBack"
    />
    <div class="chat-content"></div>
    <div class="chat-bottom">
      <van-field v-model="message" placeholder="请输入发送内容" />
      <van-button type="primary" size="small" @click="handleSend" :disabled="!message">发送</van-button>
    </div>
  </div>
</template>
<script>
  import $ from "jquery";
  export default {
    data() {
      return {
        message: '',
      }
    },
    created() {
       $('.chat-content').empty();
      // 即时聊天（参考：https://github.com/htzhanglong/koa-socket/blob/master/example/server.js）
      this.socket = io('http://118.25.208.36/chat');
      this.socket.on( 'message', (resMessage) => {
        const rightDialog = `
          <div style="display: flex; flex-direction: row-reverse; margin-bottom: 10px;">
            <div style="color: blue; width: 30px; height: 30px; text-align: center; line-height: 30px; border-radius: 50%; background-color: lightblue;">客</div>
            <div style="width: 10rem; border-radius: 5px; background-color: lightgrey; color: #fff; padding: 5px">${resMessage}</div>
          </div>
        `
        $('.chat-content').append(rightDialog);
      })
    },
    methods: {
      goBack() {
        this.$router.go(-1);
      },
      handleSend() {
        this.socket.emit('message', this.message);
        const leftDialog = `
          <div style="display: flex; margin-bottom: 10px;">
            <div style="color: red; width: 30px; height: 30px; text-align: center; line-height: 30px; border-radius: 50%; background-color: lightblue;">我</div>
            <div style="width: 10rem; border-radius: 5px; background-color: lightgrey; color: #fff; padding: 5px">${this.message}</div>
          </div>
        `
        $('.chat-content').append(leftDialog);
        this.message = '';
      },
    },
    mounted() {
      const height = document.documentElement.clientHeight;
      const chatContentHeight = document.getElementsByClassName('chat-content')[0];
      chatContentHeight.style.height = height - 44 - 46 - 20 + 'px';
    },
  }
</script>

<style scoped>
  .chat-page {
    display: flex;
    flex-direction: column;
  }
  .chat-content {
    background-color: #fff;
    padding: 10px;
    overflow-y: auto;
  }
  .chat-bottom {
    height: 44px;
    display: flex;
    width: 100%;
    position: fixed;
    bottom: 0;
  }
  .van-field {
    border-top: 1px solid lightgrey;
  }
  .van-button--small {
    height: 100%;
  }
  /* 聊天的内容 */
  .left-dialog {
    display: inline-block;
    
  }
</style>